import defaultConfig from "@/config";
import Toast from "@/utils/toast";
import { useUserStoreHook } from '@/store/user';

const loginDataStore = useUserStoreHook()
export interface LoginRespType {
	organ : ApiData.Organ;
	user : ApiData.User;
	organEmployee : ApiData.OrganEmployee;
	accessToken : string;
	openId : string;
	unionId : string;
	state : number;
	imToken : string;
	invCode : string;
	invChannel : string;
	invPaId : string;
}

export const handleLoginResp = (result : any, successCall ?: () => void, perfectCall ?: () => void) => {
	if (result.state === 1) {
		// if (result.organ.organType !== 105) {
		// 	Toast.message('机构类型不正确，无法登录');
		// 	return;
		// }
		if (result.organ.isPerfect === 0) {//信息是否完善（0-否、1-是）
			//初始化 loginData
			loginDataStore.setUserInfo(result);
			// loginDataStore.setAccessToken("");
			perfectCall && perfectCall();
			return;
		}
		//state==1  登录成功
		// 放入文件缓存
		// uni.setStorageSync(defaultConfig.loginKey, result);
		//初始化 loginData
		loginDataStore.setUserInfo(result);
		console.log("缓存用户信息跳转到首页...");
		successCall && successCall();
		if (result.isFastLogin) {
			//如果是快捷登录就不跳转
			getLogisticsData({}, null)
			return
		}
		let pathName = uni.getStorageSync(defaultConfig.loginBeforePages);
		let depUserId = uni.getStorageSync('depUserId');
		console.log('跳转；', pathName);
		setTimeout(() => {
			if (depUserId) {
				//跳关注公众号
				uni.reLaunch({
					url: "/pages/me/toolbox/web?url=" + encodeURIComponent(defaultConfig.officialUrl),
					success: () => {
						uni.removeStorage({ key: 'depUserId' });
					}
				});
			} else {
				getLogisticsData(result, (isHasBT : any) => {
					// 跳转至页面
					// pathName ||
					if (pathName) {
						uni.reLaunch({
							url: pathName
						})
					} else {
						//非汽修店跳物流代收-old
						//物流代收菜单移到了收货台，所以非汽修店跳物流代收跳收货台-2024.10.9
						if (result.organ.indId != 1) {
							uni.reLaunch({
								// url:  '/pages/bill/accountStatement/accountStatement'
								url: '/pages/recvDesk/index'
							});
							return
						}
						uni.reLaunch({
							url: isHasBT ? defaultConfig.pageIndex : '/pages/recvDesk/index'
						});
					}
				})

			}
		}, 1000)
	} else {
		perfectCall && perfectCall();
	}
};


const getLogisticsData = (result : any, cb : Function) => {
	//需求改变，默认都显示这里写死
	let isHasBT = 1
	loginDataStore.setIsHasSubsidy(isHasBT)
	uni.setStorageSync(defaultConfig.storageHasSubsidyKey, isHasBT);
	cb(isHasBT)
}

export const handleLoginReq = (result : LoginRespType, unionId : string, marketId = null, depUserId = null) => {


};